/* 基于链表的队列
 *
 *                  QUEUE
 *            +-------+------+
 *    +------ | front | back | ------+
 *    |       +-------+------+       |
 *    |                              |
 *    V           QUEUE_NODE         V
 * +------+    +------+           +------+
 * | data |    | data |           | data |
 * +------+    +------+           +------+
 * | next | -> | next | -> ... -> | NULL |
 * +------+    +------+           +------+
 */
#include "queue_base_list.h"

/* 创建节点 */
static QUEUE_NODE* create_node (int data) 
{
	QUEUE_NODE* node = malloc (sizeof (QUEUE_NODE));
	node->data = data;
	node->next = NULL;
	return node;
}

/* 销毁节点 */
static QUEUE_NODE* destroy_node (QUEUE_NODE* node) 
{
	QUEUE_NODE* next = node->next;
	free (node);
	return next;
}

/* 创建 */
QUEUE* queue_create (void) 
{
	QUEUE* queue = malloc (sizeof (QUEUE));
	queue->front = NULL;
	queue->back  = NULL;
	return queue;
}

/* 销毁 */
void queue_destroy (QUEUE* queue) 
{
	queue_clear (queue);
	free (queue);
}

/* 压入 */
void queue_push (QUEUE* queue, int data) 
{
	QUEUE_NODE* back = create_node (data);

	if (queue->back)
        {
		queue->back->next = back;
        }
	else
        {
		queue->front = back;
        }

	queue->back = back;
}

/* 弹出 */
int queue_pop (QUEUE* queue) 
{
	int data = queue->front->data;

	if (! (queue->front = destroy_node (queue->front)))
        {
		queue->back = NULL;
        }
	return data;
}



/* 清空 */
void queue_clear (QUEUE* queue) 
{

	while (queue->front)
        {
		queue->front = destroy_node (queue->front);
        }
	queue->back = NULL;
}

/* 大小 */
int queue_size (QUEUE* queue) 
{
	int size = 0;

	QUEUE_NODE* node = NULL;

	for (node = queue->front; node; node = node->next)
        {
		size++;
        }
	return size;
}

/* 判空 */
int queue_empty (QUEUE* queue) 
{
        
	if( !queue->front && !queue->back)
        {
            return 1;
        }

        return 0;
}




